package org.tacticalTroopers.jme.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tacticalTroopers.jme.common.message.Command;
import org.tacticalTroopers.jme.common.message.SerializationInitializer;

import com.jme3.network.connection.Client;
import com.jme3.network.events.ConnectionListener;
import com.jme3.network.events.MessageListener;
import com.jme3.network.message.Message;


public class NetworkManager {

	final static Log log = LogFactory.getLog(NetworkManager.class);

	TacticalTroopersServer server;

	com.jme3.network.connection.Server networkServer;

	Map<Client,NetworkClientHandler> clientToHandler = new HashMap<Client,NetworkClientHandler>();

	public void init(Integer port,TacticalTroopersServer server) throws IOException{
		SerializationInitializer.init();
		this.server = server;
		networkServer = new com.jme3.network.connection.Server(port, port+1);
		networkServer.addConnectionListener(connectionListener);
		networkServer.addMessageListener(commandMessageListener);
		networkServer.start();

	}

	ConnectionListener connectionListener = new ConnectionListener() {

		@Override
		public void clientDisconnected(Client client) {
			NetworkClientHandler current = clientToHandler.get(client);
			server.removeClientHandler(current);
		}

		@Override
		public void clientConnected(Client client) {
			NetworkClientHandler nch = new NetworkClientHandler(client,server);
			
			clientToHandler.put(client, nch);
			server.addClientHandler(nch);
			log.info("New Client created with id :"+nch.getPlayer().getId());
			//networkServer.sendTCP(arg0, object).

		}
	};


	MessageListener commandMessageListener = new MessageListener() {

		@Override
		public void objectSent(Object arg0) {}

		@Override
		public void objectReceived(Object arg0) {}

		@Override
		public void messageSent(Message arg0) {}

		@Override
		public void messageReceived(Message message) {
			NetworkClientHandler current = clientToHandler.get(message.getClient());
			if(current!=null){
				current.receiveMessage(message);
			}
		}
	};

}

